// 引入 naive-ui 组件
import { createDiscreteApi } from "naive-ui"

// 配置
export const fetchConfig = {
    baseURL: "http://demonuxtapi.dishait.cn/pc",
    headers: {
        appid: "bd9d01ecc75dbbaaefce"
    }
}

const useGetFetchOptions = (options = {}) => {
    options.baseURL = options.baseURL ?? fetchConfig.baseURL;
    options.headers = options.headers ?? fetchConfig.headers;
    options.initialCache = options.initialCache ?? false;
    options.lazy = options.lazy ?? false;

    // 用户登录,默认传token
    const token = useCookie("token");
    if (token.value) {
        options.headers.token = token.value;
    }

    return options;
}

export const useHttp = async (key, url, options = {}) => {
    options = useGetFetchOptions(options);
    options.key = key;
    if (options.$) {
        const data = ref(null);
        const error = ref(null);
        return await $fetch(url, options).then((res) => {
            data.value = res.data;
            return {
                data,
                error
            }
        }).catch((err) => {
            const msg = err?.data?.data;

            // 客户端错误处理
            if (import.meta.client) {
                const { message } = createDiscreteApi(['message'])
                message.error(msg || "服务端错误")
            }
            
            error.value = msg;
            return {
                data,
                error
            }
        })
    }



    const result = await useFetch(url, {
        ...options,
        // 响应之前的数据处理
        transform: (res) => {
            return res.data;
        },
    });



    // 客户端错误处理
    if (import.meta.client && result.error.value) {
        const msg = result.error.value.data.data;
        const { message } = createDiscreteApi(['message'])
        message.error(msg || "服务端错误")
    }

    return result;
}



/**
 * @description GET请求
 * @param { String } key 唯一值
 * @param { String } url 地址
 * @param { Object } options 参数
 */

export const useHttpGet = (key, url, options = {}) => {
    options.method = "GET";
    return useHttp(key, url, options)
}




/**
 * @description POST请求
 * @param { String } key 唯一值
 * @param { String } url 地址
 * @param { Object } options 参数
 */

export const useHttpPost = (key, url, options = {}) => {
    options.method = "POST";
    return useHttp(key, url, options)
}